<template>
  <div class="attraction-manage">
    <div class="page-header">
      <h1>景点管理</h1>
      <button @click="showAddDialog = true" class="add-btn">
        <span class="btn-icon">➕</span>
        添加景点
      </button>
    </div>

    <div class="search-bar">
      <input 
        v-model="searchKeyword" 
        @input="searchAttractions"
        placeholder="搜索景点名称..." 
        class="search-input"
      >
    </div>

    <div class="attractions-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>景点名称</th>
            <th>描述</th>
            <th>位置</th>
            <th>分类</th>
            <th>开放时间</th>
            <th>票价</th>
            <th>评分</th>
            <th>图片</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="attraction in filteredAttractions" :key="attraction.id">
            <td>{{ attraction.id }}</td>
            <td class="name-cell">{{ attraction.name }}</td>
            <td class="desc-cell">{{ attraction.description.substring(0, 40) }}...</td>
            <td>{{ attraction.location }}</td>
            <td>
              <span class="category-tag">{{ getCategoryDisplayName(attraction.category) }}</span>
            </td>
            <td>{{ attraction.openTime }}</td>
            <td>{{ attraction.ticketPrice }}</td>
            <td class="rating-cell">
              <span class="rating">⭐ {{ attraction.rating }}</span>
            </td>
            <td class="image-cell">
              <img v-if="attraction.image" :src="'http://localhost:8080/' + attraction.image" :alt="attraction.name" class="thumbnail">
              <span v-else class="no-image">无图片</span>
            </td>
            <td class="actions-cell">
              <button @click="editAttraction(attraction)" class="edit-btn">编辑</button>
              <button @click="deleteAttraction(attraction.id!)" class="delete-btn">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>{{ showAddDialog ? '添加景点' : '编辑景点' }}</h2>
          <button @click="closeDialog" class="close-btn">✕</button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="saveAttraction">
            <div class="form-group">
              <label>景点名称：</label>
              <input v-model="currentAttraction.name" type="text" required>
            </div>
            <div class="form-group">
              <label>描述：</label>
              <textarea v-model="currentAttraction.description" rows="3" required></textarea>
            </div>
            <div class="form-group">
              <label>位置：</label>
              <input v-model="currentAttraction.location" type="text" required>
            </div>
            <div class="form-group">
              <label>分类：</label>
              <select v-model="currentAttraction.category" required>
                <option value="" disabled>请选择分类</option>
                <option value="natural">自然风光</option>
                <option value="historical">历史古迹</option>
                <option value="cultural">文化景观</option>
              </select>
            </div>
             <div class="form-group">
              <label>开放时间：</label>
              <input v-model="currentAttraction.openTime" type="text">
            </div>
            <div class="form-group">
              <label>票价：</label>
              <input v-model="currentAttraction.ticketPrice" type="text">
            </div>
            <div class="form-group">
              <label>评分：</label>
              <input v-model.number="currentAttraction.rating" type="number" min="0" max="5" step="0.1" required>
            </div>
            <div class="form-group">
              <label>景点图片：</label>
              <ImageSelector v-model="currentAttraction.image" />
            </div>
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="cancel-btn">取消</button>
              <button type="submit" class="save-btn">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ImageSelector from '@/components/ImageSelector.vue'

interface Attraction {
  id?: number
  name: string
  description: string
  location: string
  rating: number
  image: string
  category: string
  openTime: string
  ticketPrice: string
}

const attractions = ref<Attraction[]>([])
const filteredAttractions = ref<Attraction[]>([])
const searchKeyword = ref('')
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const currentAttraction = ref<Attraction>({
  name: '',
  description: '',
  location: '',
  rating: 0,
  image: '',
  category: '',
  openTime: '',
  ticketPrice: ''
})

const getCategoryDisplayName = (category: string) => {
  switch (category) {
    case 'natural':
      return '自然风光'
    case 'historical':
      return '历史古迹'
    case 'cultural':
      return '文化景观'
    default:
      return category || '未分类'
  }
}

const loadAttractions = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/v1/attractions')
    if (response.ok) {
      attractions.value = await response.json()
      filteredAttractions.value = attractions.value
    }
  } catch (error) {
    console.error('加载景点数据失败:', error)
    alert('加载景点数据失败')
  }
}

const searchAttractions = () => {
  if (!searchKeyword.value.trim()) {
    filteredAttractions.value = attractions.value
  } else {
    filteredAttractions.value = attractions.value.filter(attraction =>
      attraction.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
}

const editAttraction = (attraction: Attraction) => {
  currentAttraction.value = { ...attraction }
  showEditDialog.value = true
}

const deleteAttraction = async (id: number) => {
  if (id === undefined) return;
  if (!confirm('确定要删除这个景点吗？')) return

  try {
    const response = await fetch(`http://localhost:8080/api/v1/attractions/${id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      alert('删除成功')
      loadAttractions()
    } else {
      alert('删除失败')
    }
  } catch (error) {
    console.error('删除景点失败:', error)
    alert('删除景点失败')
  }
}

const saveAttraction = async () => {
  try {
    const url = showAddDialog.value 
      ? 'http://localhost:8080/api/v1/attractions'
      : `http://localhost:8080/api/v1/attractions/${currentAttraction.value.id}`
    
    const method = showAddDialog.value ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(currentAttraction.value)
    })
    
    if (response.ok) {
      alert(showAddDialog.value ? '添加成功' : '更新成功')
      closeDialog()
      loadAttractions()
    } else {
      alert(showAddDialog.value ? '添加失败' : '更新失败')
    }
  } catch (error) {
    console.error('保存景点失败:', error)
    alert('保存景点失败')
  }
}

const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentAttraction.value = {
    name: '',
    description: '',
    location: '',
    rating: 0,
    image: '',
    category: '',
    openTime: '',
    ticketPrice: ''
  }
}

onMounted(() => {
  loadAttractions()
})
</script>

<style scoped>
.attraction-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.add-btn {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background: #229954;
}

.btn-icon {
  margin-right: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.attractions-table {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.name-cell {
  font-weight: 500;
  color: #2c3e50;
}

.desc-cell {
  max-width: 200px;
  color: #666;
}

.category-tag {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.rating-cell .rating {
  background: #f39c12;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.image-cell .thumbnail {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.no-image {
  color: #999;
  font-style: italic;
}

.actions-cell {
  white-space: nowrap;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-right: 8px;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.edit-btn:hover {
  background: #2980b9;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background: #c0392b;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h2 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-group select {
  height: 40px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-btn, .save-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
}

.cancel-btn:hover {
  background: #7f8c8d;
}

.save-btn {
  background: #27ae60;
  color: white;
}

.save-btn:hover {
  background: #229954;
}
</style> 